package com.rc.saas.tenant.job;

import com.rc.saas.tenant.common.utils.DateHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;

import java.io.*;
import java.util.Date;

/**
 * @Author: yang
 * @Date: 2022/5/8 22:59
 */
public class MysqlBackupTask {
    Logger logger = LoggerFactory.getLogger(MysqlBackupTask.class);
    /**
     * spring.datasource.driverClassName=com.mysql.cj.jdbc.Driver
     * #spring.datasource.url=jdbc:mysql://localhost:3306/jinzhuang_saas?serverTimezone=Shanghai&?useUnicode=true&characterEncoding=utf8&useSSL=false
     * <p>
     * #spring.datasource.driverClassName=com.mysql.jdbc.Driver
     * spring.datasource.url=jdbc:mysql://47.106.210.3:3306/rc_2022?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=Asia/Shanghai&zeroDateTimeBehavior=CONVERT_TO_NULL
     * #root
     * spring.datasource.username=root
     * spring.datasource.password=123456
     * spring.datasource.max-idle=10
     * spring.datasource.max-wait=10000
     * spring.datasource.min-idle=5
     * spring.datasource.initial-size=5
     */
    @Value("${spring.datasource.driverClassName}")
    String driverClassName;
    @Value("${spring.datasource.url}")
    String host;
    @Value("${spring.datasource.username}")
    String username;
    @Value("${spring.datasource.password}")
    String password;
    String database = "rc_2022";
    String backupPath = "C:";


//数据库的备份

    public static boolean exportDatabaseTool(String hostIP, String userName, String password, String savePath,

                                             String fileName, String databaseName) throws InterruptedException {

// 创建文件保存的路径

        File saveFile = new File(savePath);

        if (!saveFile.exists()) {// 如果目录不存在

            saveFile.mkdirs();// 创建文件夹

        }

        if (!savePath.endsWith(File.separator)) {

            savePath = savePath + File.separator;

        }

        PrintWriter printWriter = null;

        BufferedReader bufferedReader = null;

        try {

            printWriter = new PrintWriter(new OutputStreamWriter(new FileOutputStream(savePath + fileName), "utf8"));

            StringBuilder stringBuilder = new StringBuilder();

            stringBuilder.append("mysqldump").append(" --opt").append(" -h").append(hostIP);

            stringBuilder.append(" --user=").append(userName).append(" --password=").append(password)

                    .append(" --lock-all-tables=true");

            stringBuilder.append(" --result-file=").append(savePath + fileName).append(" --default-character-set=utf8 ")

                    .append(databaseName);

            Process process = Runtime.getRuntime().exec(stringBuilder.toString());

            InputStreamReader inputStreamReader = new InputStreamReader(process.getInputStream(), "utf8");

            bufferedReader = new BufferedReader(inputStreamReader);

            String line;

            while ((line = bufferedReader.readLine()) != null) {

                printWriter.println(line);

            }

            printWriter.flush();

            if (process.waitFor() == 0) {// 0 表示线程正常终止。

                return true;

            }

        } catch (IOException e) {

            e.printStackTrace();

        } finally {

            try {

                if (bufferedReader != null) {

                    bufferedReader.close();

                }

                if (printWriter != null) {

                    printWriter.close();

                }

            } catch (IOException e) {

                e.printStackTrace();

            }

        }

        return false;

    }


    /**
     * windows备份数据库
     */
//    public void run() {
//
//        //todo 开辟匿名线程单独执行回收企业钱包金额的功能
////        new Thread() {
////            @Override
////            public void run() {
////                recoveryAccountService.updateByExcuteRecovery();
////            }
////        }.start();
//            String user = username;
//            String password = this.password;
//            String database = "rc_2017";
//            String dbName = database + "_" + DateHelper.dataToString(new Date(), "yyyyMMdd") + ".sql";
//            String backupPath = "D://backup/db/";
//            String filepath = backupPath + dbName;
//
//            // 创建执行的批处理
//            FileOutputStream fout = null;
//            OutputStreamWriter writer = null;
//            try {
//                String batFile = backupPath + "//backup_databae.bat";
//                fout = new FileOutputStream(batFile);
//                writer = new OutputStreamWriter(fout, "utf8");
//                StringBuffer sb = new StringBuffer("");
//                sb.append("D:" + " \r\n");
//                sb.append("cd " + "D:\\runtime\\MySQL\\MySQL Server 5.5\\bin" + " \r\n");
//                sb.append("mysqldump -u " + user + " -p" + password + " " + database + " >" + filepath + "\r\n");
//                sb.append("exit");
//                String outStr = sb.toString();
//                writer.write(outStr);
//                writer.flush();
//                writer.close();
//                fout.close();
//
//                Runtime.getRuntime().exec(" cmd /c start " + batFile);
//                logger.info("备份数据库成功！");
//            } catch (Exception e) {
//                e.printStackTrace();
//                logger.error("备份数据库失败！", e);
//            } finally {
//                writer = null;
//                fout = null;
//            }
//    }
}